//
//  ScanBinaryCodeViewController.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/3.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
import AVFoundation
import RxSwift
class ScanBinaryCodeViewController: BaseViewController,AVCaptureMetadataOutputObjectsDelegate,UITableViewDelegate,UITableViewDataSource {
    
    var scanObj : RJScanNative?
    var date: Date?
    let bag = DisposeBag()
    let resume = UIButton.init(type: .system)
    let datePicker = UIDatePicker(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    let field = UITextField()
    override func viewDidLoad() {
        super.viewDidLoad()
        datePicker.locale = Locale.init(identifier: "zh_CN")
        datePicker.backgroundColor = UIColor.white
        datePicker.datePickerMode = .date
        self.view.addSubview(field)
        field.inputView = datePicker
        field.inputAccessoryView = self.toolbarview
        self.navigationController?.isNavigationBarHidden = true
        self.view.backgroundColor = UIColor.white
        addOpaLayer()
        startScan()
        resume.setTitle("停止", for: .normal)
        resume.setTitleColor(UIColor.white, for: .normal)
        self.view.addSubview(resume)
        resume.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(60 * YXHeightScale)
            make.width.equalTo(80)
            make.height.equalTo(30)
        }
        resume.rx.tap.subscribe(onNext: { [weak self]() in
            if (self?.scanObj?.scanning() ?? false) {
                self?.stopScan()
                self!.resume.setTitle("扫描", for: .normal)
            } else {
                self?.startScan()
                self!.resume.setTitle("停止", for: .normal)
            }
        }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: self.bag)
        // Do any additional setup after loading the view.
    }
    
    func startScan() -> Void {
        let result = RJScanWrapper.isGetCameraPermission()
        if result == false {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 1), execute: {
                self.alert("请开启相机权限", cancelTitle: "取消", cancelBlock: nil, sureTitle: "确定", sureBlock: {
                    UIApplication.shared.openURL(URL.init(string: UIApplication.openSettingsURLString)!)
                })
            })
            self.stopScan()
            return
        } else {
            if scanObj == nil {
                weak var weakSelf = self
                let originX = 150 * YXWidthScale
                let wid = (YXDeviceWidth - 300 * YXWidthScale)
                let originY = 120 * YXHeightScale
                let rect = configInsterestRect(original: CGRect.init(x: originX, y: originY, width: wid, height: wid))
                scanObj = RJScanNative.init(preView: self.view, success: { (arr) in
                    weakSelf!.scanResult(array: arr!)
                }, insterRect: rect)
            }
            scanObj!.startScan()
            self.scan?.startScan()
            resume.setTitle("停止", for: .normal)
        }
    }
    
    func stopScan(){
        resume.setTitle("扫描", for: .normal)
        self.scanObj?.stopScan()
        self.scan?.stopScan()
    }
    
    var scan: Scan?
    
    var url: String?
    
    
    var code = ""
    
    func scanResult(array : Array<RJScanResult>) -> Void {
        guard array.count > 0 else {
            return
        }
        let result = array.first
        if result != nil {
            //url
            if let url = result?.strScanned {
                if url.count > 33 {
                    let id = url.suffix(32)
                    self.url = String(id)
                    let cod = url[url.index(after: url.startIndex) ..< url.range(of: self.url!)!.lowerBound]
                    self.code = String(cod)
                    self.source.append(self.code)
                    self.refresh()
                } else {
                    self.alert("非法的二维码")
                }
            }
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 2000)) {
            self.scanObj?.startScan()
        }
    }
    
    func refresh(){
        self.beginLoading()
        let time = self.date?.dateLineStr ?? ""
        NetManager.get(PhoneScan, ["id": self.url ?? "","actuallyPayTime": time], suc: { (json) in
            self.endLoading()
            if json["success"].bool == false {
                self.alert(json["errorMsg"].string)
                self.source.removeLast()
                return
            } else {
                self.tableView.reloadData()
            }
        }) { (error) in
            self.endLoading()
            self.alert(error.localizedDescription)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        self.navigationController?.isNavigationBarHidden = false
    }
    
    func addOpaLayer() -> Void {
        let opaue = UIView.init()
        opaue.frame = self.view.bounds
        opaue.alpha = 0.5
        opaue.backgroundColor = UIColor.black
        self.view.addSubview(opaue)
        let back = UIButton.init(type: .system)
        back.frame = CGRect.init(origin: CGPoint.init(x: 30 * YXWidthScale, y: 60 * YXHeightScale), size: CGSize.init(width: YXWidthScale * 32, height: YXHeightScale * 32))
        back.tintColor = UIColor.white
        let image = UIImage.init(named: "nav_scan_close")
        back.setImage(image, for: .normal)
        back.addTarget(self, action: #selector(pop), for: .touchUpInside)
        opaue.addSubview(back)

        let shape = CAShapeLayer.init()
        let path = UIBezierPath.init(rect: self.view.bounds)
        let originX = 150 * YXWidthScale
        let wid = (YXDeviceWidth - 300 * YXWidthScale)

        let originY = 120 * YXHeightScale

        let p = UIBezierPath.init(rect: CGRect.init(origin: CGPoint.init(x: originX, y: originY), size: CGSize.init(width: wid, height: wid)))
        if self.scan == nil {
            self.scan = Scan.init(frame: CGRect.init(origin: CGPoint.init(x: originX, y: originY), size: CGSize.init(width: wid, height: wid)))
            self.view.addSubview(self.scan!)
        }
        self.scan?.startScan()
        path.append(p.reversing())
        shape.path = path.cgPath
        shape.fillColor = UIColor.red.cgColor
        opaue.layer.mask = shape
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)
        tableView.backgroundColor = UIColor.white
        tableView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(originY + wid + 20 * YXHeightScale)
        }
        tableView.tableFooterView = UIView()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.tableView.reloadData()
    }
    
    let tableView = UITableView.init(frame: .zero, style: .plain)
    
    
    func configInsterestRect(original : CGRect) -> CGRect {
        let size = self.view.bounds.size;
        let p1 = size.height / size.width
        let p2 = CGFloat(1920.0) / CGFloat(1080.0)
        if p1 < p2 {
            let fixHeight = size.width * 1920.0 / 1080.0
            let fixPadding = (fixHeight - size.height) / 2
            return CGRect.init(x: (original.origin.y + fixPadding)/fixHeight, y: original.origin.x/size.width, width: original.size.height / fixHeight, height: original.size.width / size.width)
        }else{
            let fixWidth = self.view.bounds.size.height * 1080.0 / 1920.0;
            let fixPadding = (fixWidth - size.width) / 2;
            return CGRect.init(x: original.origin.y / size.height, y: (original.origin.x + fixPadding) / fixWidth, width: original.size.height / size.height, height: original.size.width / fixWidth)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    var source: [String] = []
    
    override func endedit() {
        super.endedit()
        self.date = self.datePicker.date
        self.startScan()
        self.tableView.reloadData()
    }
    
}


extension ScanBinaryCodeViewController{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.source.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
        if cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "UITableViewCell")
            cell?.textLabel?.numberOfLines = 0
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 14)
            cell?.textLabel?.lineBreakMode = .byCharWrapping
            cell?.textLabel?.text = self.source[indexPath.row] + "已确认"
            cell?.selectionStyle = .none
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.white
        let label = UILabel()
        label.textColor = UIColor.hex("999999")
        label.text = "报销日期:" + self.date!.dateLineStr
        label.font = UIFont.systemFont(ofSize: 14)
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(15)
        }
        let button = UIButton.init(type: .system)
        button.addTarget(self, action: #selector(popKeyBoard), for: .touchUpInside)
        view.addSubview(button)
        button.setTitle("更改日期", for: .normal)
        button.setTitleColor(UIColor.mainColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-15)
            make.width.equalTo(80)
            make.height.equalToSuperview()
        }
        
        return view
    }
    
    @objc func popKeyBoard(){
        self.field.becomeFirstResponder()
    }
}
